//
//  HistoryAccess.m
//  ZingBrowser
//
//  Created by -Xh- on 3/1/13.
//  Copyright (c) 2013 -Xh-. All rights reserved.
//

#import "HistoryAccess.h"
#import "StaticVariables.h"
@implementation HistoryAccess


-(NSMutableArray *)getRecordsFromSelectQuery:(NSString *)_query{
    NSMutableArray* historyArray=[[NSMutableArray alloc]init];
    [database open];
    FMResultSet* queryResult=[database executeQuery:_query];
    while ([queryResult next]) {
        HistoryModel* currentHistory=[[HistoryModel alloc]init];
        currentHistory.historyID=[queryResult stringForColumn:@"HistoryID"];
        currentHistory.title=[queryResult stringForColumn:@"Title"];
        currentHistory.url=[queryResult stringForColumn:@"Url"];
        currentHistory.favIcon=[queryResult dataForColumn:@"FavIcon"];
        currentHistory.dateAdded=[queryResult dateForColumn:@"DateAdded"];
        [historyArray addObject:currentHistory];
    }
    [database close];
    return historyArray;

}

-(NSMutableArray *)getAllRecords{
    return [self getRecordsFromSelectQuery:@"SELECT * FROM HISTORY"];
}
-(NSMutableArray *)getAllRecordsOrderByDate{
    return [self getRecordsFromSelectQuery:@"SELECT * FROM HISTORY GROUP BY Url ORDER BY DateAdded DESC"];

}

-(NSMutableArray *)getAllRecordsExceptSpeedDial{
    //SELECT * FROM HISTORY WHERE Url NOT IN (SELECT Url FROM SPEEDDIAL) GROUP BY Url ORDER BY DateAdded DESC
    return [self getRecordsFromSelectQuery:@"SELECT * FROM HISTORY WHERE Url NOT IN (SELECT Url FROM SPEEDDIAL) GROUP BY Url ORDER BY DateAdded DESC"];
}

-(NSMutableArray *)getAllRecordsOnSpecificDate:(NSDate *)_date{
    double numberOfSecondsOnOneDay=60*60*24;
    NSString* queryDateString=[MyUtilities getCorrectDateFormatFromDate:_date];
    NSString* nextDateString=[MyUtilities getCorrectDateFormatFromDate:[_date dateByAddingTimeInterval:numberOfSecondsOnOneDay]];
    NSString* queryString=[NSString stringWithFormat:@"SELECT * FROM HISTORY WHERE DateAdded BETWEEN date('%@') AND date('%@') GROUP BY Url ORDER BY DateAdded DESC",queryDateString,nextDateString];
    //NSLog(@"specific : %@",queryString);
    return [self getRecordsFromSelectQuery:queryString];

}
-(NSMutableArray *)getAllRecordsBetweenDate:(NSDate *)_dateBegin andDate:(NSDate *)_dateEnd{
    double numberOfSecondsOnOneDay=60*60*24;
    NSString* beginString=[MyUtilities getCorrectDateFormatFromDate:_dateBegin];
    NSString* endString=[MyUtilities getCorrectDateFormatFromDate:[_dateEnd dateByAddingTimeInterval:numberOfSecondsOnOneDay]];
    NSString* queryString=[NSString stringWithFormat:@"SELECT * FROM HISTORY WHERE DateAdded BETWEEN date('%@') AND date('%@') GROUP BY Url ORDER BY DateAdded DESC",beginString,endString];
    //NSLog(@"between : %@",queryString);
    return [self getRecordsFromSelectQuery:queryString];
}

-(BOOL)insert:(BaseModel *)_object{
    //the model to be inserted into database, we get this from the viewController
    HistoryModel* insertingHistory=(HistoryModel*)_object;
    //the BOOL value to indicate if the operation succeed or fail.
    bool success;
    
    //First we check whether the insertingHistory is already on DB or not.
    //HistoryModel* recordOnDB=(HistoryModel*)[self findByURL:insertingHistory.url];
    //If we already have that record on DB, just update the date.
    //Else, we will insert it into DB.
    [database open];
    
        NSString* modifiedTitle=[insertingHistory.title stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
        NSString* insertQuery=[NSString stringWithFormat:@"INSERT INTO HISTORY (HistoryID, Title, Url, FavIcon,DateAdded) VALUES ('%@','%@','%@','%@','%@')",insertingHistory.historyID,modifiedTitle,insertingHistory.url,insertingHistory.favIcon,insertingHistory.dateAdded];
        success = [database executeUpdate:insertQuery];
//    if(success){
//        NSLog(@"inserted : %@ - %@",insertingHistory.historyID, insertingHistory.url);
//    }else{
//        NSLog(@"insert failed");
//    }
    
    [database close];
    return success;
}

-(void)insertWith:(NSString *)_title AndURL:(NSString *)_url{
    HistoryModel* currentHistory=[[HistoryModel alloc]initWithTitle:_title AndURL:_url];
    
    int lastInsertedIDNumber=[self getLastIDNumber];
    [currentHistory generateIDWithNumber:lastInsertedIDNumber+1];
    UIImage* presetImage=[MyUtilities getImageWithURL:currentHistory.url FromDict:[[StaticVariables shareVariables]presetDialerURLDic]];
    
    if(presetImage!=nil){
        currentHistory.favIcon=nil;
    }else{
        //NSString* favIconString=[[[StaticVariables shareVariables]stringResource]defaultFavIconString];
        currentHistory.favIcon = [[NSData alloc]init];//[favIconString dataUsingEncoding:NSUTF8StringEncoding];
        
    }
    BOOL success = [self insert:currentHistory];
    
}




-(BaseModel *)findByURL:(NSString *)_url{
    //the result to return
    HistoryModel* currentHistory=[[HistoryModel alloc]init];
    [database open];
    NSString* queryString=[NSString stringWithFormat:@"SELECT * FROM HISTORY WHERE Url='%@'",_url];
    FMResultSet* queryResult=[database executeQuery:queryString];
    if([queryResult next]){
        currentHistory.historyID=[queryResult stringForColumn:@"HistoryID"];
        currentHistory.title=[queryResult stringForColumn:@"Title"];
        currentHistory.url=[queryResult stringForColumn:@"Url"];
        currentHistory.favIcon=[queryResult dataForColumn:@"FavIcon"];
        currentHistory.dateAdded=[queryResult dateForColumn:@"DateAdded"];
    }else{
        currentHistory=nil;
    }
    [database close];
    return currentHistory;

}

-(int)getLastIDNumber{
    NSMutableArray* recordsArray=[self getAllRecords];
    int allRecordCount=recordsArray.count;
    if(allRecordCount==0){
        return -1;
    }else{
        HistoryModel* lastInsertedRecord=[recordsArray objectAtIndex:recordsArray.count-1];
        int idNumber=[lastInsertedRecord getNumberFromID];
        return idNumber;
        
    }
}
-(BOOL)deleteObjectAtID:(NSString *)_id{
    BOOL success;
    [database open];
    NSString* deleteQuery=[NSString stringWithFormat:@"DELETE FROM HISTORY WHERE HistoryID='%@'",_id];
    success=[database executeUpdate:deleteQuery];
    [database close];
    return success;
}

-(BOOL)deleteObjectAtURL:(NSString *)_url{
    BOOL success;
    [database open];
    NSString* deleteQuery=[NSString stringWithFormat:@"DELETE FROM HISTORY WHERE Url='%@'",_url];
    success=[database executeUpdate:deleteQuery];
    [database close];
    return success;
}
-(BOOL)deleteAll{
    BOOL success;
    [database open];
    NSString* deleteQuery=[NSString stringWithFormat:@"DELETE FROM HISTORY"];
    success=[database executeUpdate:deleteQuery];
    [database close];
    return success;
}

-(NSMutableArray *)getRecordsBySearchTerm:(NSString *)searchTerm{
    NSString* searchQuery = [NSString stringWithFormat:@"SELECT * FROM HISTORY WHERE Title LIKE '%%%@%%' OR Url LIKE '%%%@%%' GROUP BY Url ORDER BY DateAdded DESC",searchTerm,searchTerm];
    return [self getRecordsFromSelectQuery:searchQuery];
}

@end
